package com.tristen.gulimall.gateway.filters;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.tristen.gulimall.gateway.entity.WhiteUrlEntity;
import com.tristen.gulimall.gateway.service.WhiteUrlService;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * 认证全局过滤器
 *
 * @author: lxc
 * @date: 2022/1/8 - 23:44
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    private WhiteUrlService whiteUrlService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();
        List<WhiteUrlEntity> whiteUrlEntityList = whiteUrlService.list();
        //进行白名单匹配
        if (CollectionUtil.isNotEmpty(whiteUrlEntityList)) {
            long count = whiteUrlEntityList.stream()
                    .filter(e -> (e.getMatchStatus() == 0 && StrUtil.containsIgnoreCase(path, e.getUrl()))
                            || (e.getMatchStatus() == 1 && StrUtil.equalsIgnoreCase(path, e.getUrl()))
                    )
                    .count();
            if (count >= 1) {
                //匹配白名单时，直接放行
                return chain.filter(exchange);
            }
        }
        //todo 鉴权

        return chain.filter(exchange);
    }

    /**
     * 设置过滤器加载顺序，返回值越小，优先级越高
     *
     * @return 过滤器加载顺序
     */
    @Override
    public int getOrder() {
        return 10;
    }
}
